#include "kportbench.h"
#include "ui_kportbench.h"
#include <QDebug>

kportBench::kportBench(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::kportBench)
{
    x = new float[300];
    y = new float[300];
    yInt = new float[300];
    lastread = 0;
    for(int i = 0; i< 300; i++)
    {
        x[i] = 0.01*i;
        y[i] = 0;
        yInt[i]  = 0;
    }
    ui->setupUi(this);
    qmgl = new QMathGL(this);
    c = new Curve();
    c->addCurve(QPair<float*, float*>(x,y),300);
    c->addCurve(QPair<float*, float*>(x,yInt),300);
    qmgl->setDraw(c);
    qmgl->setRotate(true);
    qmgl->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    qmgl->setSize(700, 600);
    qmgl->setAlpha(false);
    qmgl->update();
    ui->horizontalLayout->addWidget(qmgl);
    QVector<QString> axis;
    axis << "T(S)" << "Throughput(MB)";
    c->setAxis(axis);
    connect(&timer, SIGNAL(timeout()), this, SLOT(updateGraph()));
    w.start();
    lasttime = QTime::currentTime();
    timer.start(10);
    qmgl->setUpdatesEnabled(true);
}

kportBench::~kportBench()
{
    delete ui;
}

void kportBench::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void kportBench::closeEvent(QCloseEvent *)
{
    qmgl->exportEPS("out.eps");
}

void kportBench::updateGraph()
{
    uint io = w.getIO();
    if(lastread > io)
    {
        lastread= io;
        return;
    }
    QTime now = QTime::currentTime();
    int msecDiff = abs(now.msecsTo(lasttime));
    lasttime = now;
    if(sample != 0)
    {
        memmove((y+1),y, (300-1)*sizeof(float));
        memmove((x+1),x, (300-1)*sizeof(float));
    }
    y[0] = (io - lastread)/(1024.0*1024.0);
    x[0] = x[1] - msecDiff/1000.0;
    sample++;
    lastread = io;
    if(sample%100 == 0)
    {
        float accum = 10;
        for(int i = 1; i<300; i++)
        {
            if(accum > 1.0)
            {
                accum = x[i+1] - x[i];
                yInt[i] = y[i];
            }
            else
            {
                yInt[i] = yInt[i - 1] + y[i];
                accum += x[i+1] - x[i];
            }
            qDebug() << accum;
        }
        qmgl->repaint();
        qmgl->update();
        if(yInt[99] != 0)
        {
            if((yInt[99] == yInt[199]) & (yInt[199] == yInt[299]))
            {
                //this->close();
            }
        }
    }

}


